import os
import subprocess
import sys
import time
import shutil
from pathlib import Path

def find_allure_command():
    """查找allure命令的路径"""
    # 检查常见的Allure安装位置
    possible_paths = [
        # 用户自定义路径 - 可以在这里添加您的Allure安装路径
        os.environ.get("ALLURE_HOME", ""),
        # 常见安装路径
        r"C:\Program Files\allure\bin\allure.bat",
        r"C:\allure\bin\allure.bat",
        # 在PATH中查找
        shutil.which("allure"),
        shutil.which("allure.bat")
    ]
    
    # 过滤掉空值和不存在的路径
    valid_paths = [path for path in possible_paths if path and os.path.exists(path)]
    
    if valid_paths:
        return valid_paths[0]
    return None

def run_tests():
    """运行测试并自动生成报告"""
    # 确保报告目录存在
    reports_dir = Path("reports")
    allure_results_dir = reports_dir / "allure-results"
    allure_report_dir = reports_dir / "allure-report"
    
    reports_dir.mkdir(exist_ok=True)
    allure_results_dir.mkdir(exist_ok=True)
    allure_report_dir.mkdir(exist_ok=True)
    
    # 运行pytest测试
    print("正在运行测试...")
    pytest_cmd = [sys.executable, "-m", "pytest"]
    
    # 添加命令行参数
    if len(sys.argv) > 1:
        pytest_cmd.extend(sys.argv[1:])
    
    # 运行测试 - 不检查返回码，因为测试失败时也需要生成报告
    test_result = subprocess.run(pytest_cmd)
    test_failed = test_result.returncode != 0
    
    if test_failed:
        print(f"测试执行失败，返回码: {test_result.returncode}")
    
    # 查找allure命令
    allure_cmd = find_allure_command()
    
    # 生成Allure报告
    print("\n正在生成Allure报告...")
    if allure_cmd:
        try:
            # 生成HTML报告
            print(f"使用Allure命令: {allure_cmd}")
            subprocess.run([allure_cmd, "generate", str(allure_results_dir), "-o", 
                           str(allure_report_dir), "--clean"], check=True)
            
            # 打开报告
            print(f"\n报告已生成到: {allure_report_dir.absolute()}")
            print("正在打开报告...")
            
            # 尝试打开报告
            try:
                if os.name == 'nt':  # Windows
                    os.startfile(allure_report_dir / "index.html")
                else:  # macOS or Linux
                    subprocess.run(["open" if sys.platform == "darwin" else "xdg-open", 
                                   str(allure_report_dir / "index.html")])
            except Exception as e:
                print(f"无法自动打开报告: {e}")
                print(f"请手动打开: {allure_report_dir / 'index.html'}")
                
        except Exception as e:
            print(f"生成报告时出错: {e}")
    else:
        print("错误: 未找到allure命令。请确保已安装Allure并添加到PATH环境变量中。")
        print("您可以通过以下方式解决此问题:")
        print("1. 确保Allure已正确安装")
        print("2. 将Allure的bin目录添加到系统PATH环境变量中")
        print("3. 设置ALLURE_HOME环境变量指向Allure安装目录")
        print("4. 重启终端或IDE以使环境变量生效")
        print("\n安装指南: https://docs.qameta.io/allure/#_installing_a_commandline")
        
        # 尝试提供HTML报告作为备选方案
        try:
            print("\n正在尝试生成简单HTML报告作为备选...")
            html_report_path = reports_dir / "report.html"
            
            # 不检查返回码，因为测试失败时也需要生成报告
            html_result = subprocess.run([sys.executable, "-m", "pytest", "--html", str(html_report_path), "--self-contained-html"])
            
            if os.path.exists(html_report_path):
                print(f"HTML报告已生成: {html_report_path.absolute()}")
                
                # 尝试打开HTML报告
                try:
                    if os.name == 'nt':  # Windows
                        os.startfile(html_report_path)
                    else:  # macOS or Linux
                        subprocess.run(["open" if sys.platform == "darwin" else "xdg-open", str(html_report_path)])
                except Exception as e:
                    print(f"无法自动打开HTML报告: {e}")
            else:
                print("HTML报告生成失败")
        except Exception as e:
            print(f"生成HTML报告时出错: {e}")

if __name__ == "__main__":
    run_tests()